<template>
  <div class="app-container"  style="margin-top: 90px;">
    <el-button type="primary" @click="queryPatient" >会员查询</el-button>
    <el-button type="primary" @click="addPatient" >新增会员</el-button>
    <br>
    <br>


    <el-tabs v-if="editableTabs && editableTabs.length != 0" v-model="editableTabsValue" type="border-card" closable @tab-remove="removeTab">
      <el-tab-pane
        v-for="item in editableTabs"
        :key="item.name"
        :label="item.title"
        :name="item.name"
      >
        <!-- get patient list -->
        <div v-if="editableTabsValue == '1'">
          <div class="header">
            <div style="display: flex;flex-direction: column;justify-content: end;width: 60%;">
              <el-form :model="query" ref="query" label-width="80px">
                <el-row :gutter=10>
                  <el-col :span=14>
                    <el-form-item label-width="250px" label="姓名/编号/电话(后四位)/身份证号" prop="name" >
                        <el-input v-model="query.name" placeholder="请输入姓名/编号/电话(后四位)/身份证号"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span=10>
                    <el-form-item>
                      <el-button type="primary" icon="el-icon-search" @click="search" >搜索</el-button>
                      <el-button @click="resetForm('query')">重置</el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>

            <!-- <el-card class="box-card" v-for="report in reports" :key="report.jobOfficeId"  >
              <div slot="header" class="clearfix">
                <span>{{ report.jobOfficeName }}</span>
              </div>
              <div class="text item">
                {{'候诊人数: ' + report.waitingCount }}
              </div>
              <div class="text item">
                {{'就诊人数: ' + report.doingCount }}
              </div>
            </el-card> -->
          </div>
          <el-table
            v-loading="patientListLoading"
            :data="patientList"
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
          > 
            <el-table-column align="center" label="序号" width="50">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column label="编号" width="100" align="center">
              <template slot-scope="scope">
                {{ scope.row.code }}
              </template>
            </el-table-column>
            <el-table-column label="姓名" width="100" align="center">
              <template slot-scope="scope">
                {{ scope.row.name }}
              </template>
            </el-table-column>
            <el-table-column label="手机号" width="80" align="center">
              <template slot-scope="scope">
                {{ scope.row.phone }}
              </template>
            </el-table-column>
            <el-table-column label="身份证号" width="170" align="center">
              <template slot-scope="scope">
                {{ scope.row.idCard }}
              </template>
            </el-table-column>
            <el-table-column label="性别" width="50" align="center">
              <template slot-scope="scope">
                {{ scope.row.sex }}
              </template>
            </el-table-column>
            <el-table-column label="出生年月" width="120" align="center">
              <template slot-scope="scope">
                {{ scope.row.birthday + ' ' }} {{ scope.row.birthdayType | birthdayTypeFilter }} 
              </template>
            </el-table-column>
            <el-table-column label="年龄" width="50" align="center">
              <template slot-scope="scope">
                {{ scope.row.age }}
              </template>
            </el-table-column>
            <el-table-column label="入籍时长" width="120" align="center">
              <template slot-scope="scope">
                {{ scope.row.joinDuration }}
              </template>
            </el-table-column>
            <el-table-column label="就诊状态" width="100" align="center">
              <template slot-scope="scope">
                {{ scope.row.visitStatus }}
              </template>
            </el-table-column>
            <el-table-column label="会员等级" width="80" align="center">
              <template slot-scope="scope">
                {{ scope.row.vipLevel?scope.row.vipLevel:'V0' }}
              </template>
            </el-table-column>
            <el-table-column label="就诊日期" width="130" align="center">
              <template slot-scope="scope">
                {{ scope.row.visitDate }}
              </template>
            </el-table-column>
            <el-table-column class-name="status-col" :label="'信息查询\n信息修改\n等级设置'" align="center" width="100" >
              <template slot-scope="scope">
                <el-button type="primary" @click="optionPatient(scope.row)">操作</el-button>
                <!-- <el-dropdown size="medium" trigger="click" @command="optionPatient" >
                  <el-button type="primary">
                    操作<i class="el-icon-arrow-down el-icon--right"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="composeValue(scope.row, 1)" >基础信息查询</el-dropdown-item>
                    <el-dropdown-item :command="composeValue(scope.row, 2)" >基础信息修改</el-dropdown-item>
                    <el-dropdown-item :command="composeValue(scope.row, 3)" >会员等级设置</el-dropdown-item>
                    <el-dropdown-item :command="composeValue(scope.row, 4)" divided >会员就诊记录查询</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown> -->
                <!-- <el-button type="warning"  @click="toGuidance(scope.row)" size="small">挂号</el-button>
                <el-button type="primary"  @click="getInfo(scope.row)" size="small">详情</el-button>
                <el-button type="success"  @click="update(scope.row)" size="small">修改</el-button>
                <el-button type="danger" @click="deleteInfo(scope)" size="small">删除</el-button> -->
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            background
            layout="->, total, prev, pager, next"
            :total="total"
            :current-page="currentPage"
            :page-size="pageSize"
            @current-change="clickCurPage"
            >
          </el-pagination>
        </div>

        <!-- add patient -->
        <div v-else-if="editableTabsValue == '2'">
          <el-form ref="addPatientForm" :model="addPatientForm" label-width="120px" :rules="addPatientFormRules">
            <el-row :gutter="10">
              <!-- <el-col :span=8 >
                <el-form-item label="编号">
                  <el-input v-model="addPatientForm.code" />
                </el-form-item>
              </el-col> -->
              <el-col :span=6 >
                <el-form-item label="姓名" prop="name">
                  <el-input v-model="addPatientForm.name" @input="isWarnExistName = true"/>
                </el-form-item>
              </el-col>
              <el-col :span=6 >
                <el-form-item label="性别" prop="sex">
                  <el-select v-model="addPatientForm.sex" placeholder="请选择">
                    <el-option
                      v-for="item in sexEnum"
                      :key="item"
                      :label="item"
                      :value="item">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span=5 >
                <el-form-item label="联系人电话1" prop="phone">
                  <el-input v-model="addPatientForm.phone" @input="inputPhone" maxlength="11" />
                </el-form-item>
              </el-col>
              <el-col :span=5 >
                <el-form-item label="联系人电话2" >
                  <el-input v-model="addPatientForm.phoneTwo" @input="inputPhone" maxlength="11" />
                </el-form-item>
              </el-col>
              <el-col :span=9 >
                <el-form-item label="身份证号" prop="idCard">
                  <el-input v-model="addPatientForm.idCard" @input="inputIdCard" maxlength="18" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span=5 >
                <el-form-item label="其他联系人电话1" >
                  <el-input v-model="addPatientForm.phoneThree" @input="inputPhone" maxlength="11" />
                </el-form-item>
              </el-col>
              <el-col :span=5 >
                <el-form-item label="其他联系人电话2" >
                  <el-input v-model="addPatientForm.phoneFour" @input="inputPhone" maxlength="11" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span=4 >
                <el-form-item label="出生日期" prop="birthday">
                  <el-date-picker v-model="addPatientForm.birthday" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" @change="changeBirthday"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span=4 :offset=2>
                <el-form-item label="农历/公历" prop="birthdayType">
                  <el-select v-model="addPatientForm.birthdayType" placeholder="请选择">
                    <el-option
                      v-for="item in birthdayTypeEnum"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span=4 :offset=2>
                <el-form-item label="年龄">
                  <el-input v-model="addPatientForm.age" type="Number" min=0 />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span=8 >
                <el-form-item label="来源" prop="source">
                  <el-select v-model="addPatientForm.source" placeholder="请选择">
                    <el-option
                      v-for="item in sourceEnum"
                      :key="item.id"
                      :label="item.source"
                      :value="item.id"
                      @click.native="changeSource(item.id, addPatientForm)"
                      >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span=8 >
                <el-form-item label="介绍人" v-if="addPatientForm.source == 1 || addPatientForm.source == 2" >
                  <el-select v-if="addPatientForm.source == 1" v-model="addPatientForm.introducer" placeholder="请选择" :disabled="addPatientForm.introducerDisable">
                    <el-option
                      v-for="item in patientEnum"
                      :key="item.id"
                      :label="item.code + ' - ' +item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                  <el-select v-else-if="addPatientForm.source == 2" v-model="addPatientForm.introducer" placeholder="请选择" :disabled="addPatientForm.introducerDisable">
                    <el-option
                      v-for="item in userEnum"
                      :key="item.id"
                      :label="item.jobNumber + ' - ' + item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <div style="width:100%;border: 2px solid #E4E7ED;padding: 10px;">
              <div v-for="(address, index) in addPatientForm.addressList" :key="index" >
                <el-button v-if="index != 0" type="danger" icon="el-icon-delete" circle @click="deleteAddress(address, addPatientForm.addressList)"></el-button>
                <el-row :gutter="10" v-if="index != 0">
                  <el-col :span=6>
                    <el-form-item label="多址说明" prop="multiAddressDes">
                      <el-select v-model="address.multiAddressDes" placeholder="请选择" >
                        <el-option
                          v-for="item in multiAddressDesEnum"
                          :key="item"
                          :label="item"
                          :value="item"
                          @click.native="changeMultiAddressDes(item, address)"
                        >
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span=6>
                    <el-form-item label="说明填写" v-if="address.isOtherAddress == 1" prop="multiAddressDesOther">
                      <el-input v-model="address.multiAddressDesOther"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="10">
                  <el-col :span=6 >
                    <el-form-item label="省/市/区" prop="addressPre">
                      <el-cascader
                        size="large"
                        :options="options"
                        v-model="address.addressPre"
                        @change="handleChange"
                        :props="{ value: 'label', label: 'label'}"
                      >
                      </el-cascader>
                    </el-form-item>
                  </el-col>
                  <el-col :span=6>
                    <el-form-item label="小区" prop="addressMid">
                      <el-input v-model="address.addressMid"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span=10 >
                    <el-form-item label="详细地址" prop="addressInfo">
                      <el-input v-model="address.addressInfo"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="10">
                  <el-col :span=6 >
                    <el-form-item label="距离" prop="retailStore">
                      <el-select v-model="address.retailStore" placeholder="门店请选择" >
                        <el-option
                          v-for="item in deptEnum"
                          :key="item"
                          :label="item"
                          :value="item"
                        >
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span=8 >
                    <el-form-item label="公交站数" prop="distance">
                      <el-input v-model="address.distance" type="Number" min=0 />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-divider></el-divider>
              </div>
              <el-button type="primary" @click="addAddress">添加地址</el-button>
            </div>
            <el-button type="primary" @click="confirm">确 定</el-button>
          </el-form>
        </div>

        <!-- patient detail -->
        <div v-else>
          <el-container>
            <el-main>
              <el-row :gutter=10>
                  <el-col :span=24><span style="font-size: 16px;">就诊状态: 今日无就诊</span></el-col>
              </el-row>
              <el-collapse >
                <el-collapse-item name="1">
                  <template slot="title">
                    <el-row :gutter=10>
                      <el-col :span=24>
                        <span class="main-head-title">基础信息: </span>
                        <span class="main-head-title">
                          {{item.content.code + ' '}}
                          {{item.content.name + ' '}}
                          {{item.content.sex + ' '}}
                          {{item.content.age + '周岁 /'}}
                          {{'手机尾号:'+ item.content.phone + ' /'}}
                          {{'身份证号:'+ item.content.idCard + ' /'}}
                          {{'出生日期:'+ item.content.birthday + ' '}}{{item.content.birthdayType | birthdayTypeFilter}}{{' /'}}
                          {{'会员等级:'}}{{item.content.vipLevel?item.content.vipLevel:'V0' }}
                        </span>
                      </el-col>
                    </el-row>
                  </template>
                    <el-row :gutter=10>
                      <el-col :span=24>
                        <span class="main-head-title">就诊信息: </span>
                        <span class="main-head-title">
                          就诊信息内容
                        </span>
                        </el-col>
                    </el-row>
                    <el-row :gutter=10>
                      <el-col :span=24>
                        <span class="main-head-title">卡券信息: </span>
                        <span class="main-head-title">卡券信息内容 </span>
                      </el-col>
                    </el-row>
                    <el-row :gutter=10>
                      <el-col :span=24>
                        <span class="main-head-title">用药信息: </span>
                        <span class="main-head-title">用药信息内容 </span>
                      </el-col>
                    </el-row>
                    <el-row :gutter=10>
                      <el-col :span=24>
                        <span class="main-head-title">预案信息: </span>
                        <span class="main-head-title">预案信息内容</span>
                      </el-col>
                    </el-row>
                    <el-row :gutter=10>
                      <el-col :span=24>
                        <span class="main-head-title">诊断信息: </span>
                        <span class="main-head-title">诊断信息内容</span>
                      </el-col>
                    </el-row>
                    <el-row :gutter=10>
                      <el-col :span=24>
                        <span class="main-head-title">就诊习惯: </span>
                        <span class="main-head-title">就诊习惯内容</span>
                      </el-col>
                    </el-row>
                </el-collapse-item>
              </el-collapse>

              <el-tabs v-if="item.content.patientTabs && item.content.patientTabs.length != 0" v-model="item.content.patientTabsValue" type="border-card" closable @tab-remove="(targetName) => removePatientTab(targetName, item.content)">
                <el-tab-pane
                  v-for="patientTab in item.content.patientTabs"
                  :key="patientTab.name"
                  :label="patientTab.title"
                  :name="patientTab.name"
                >
                <div v-if="item.content.patientTabsValue == '会员基础信息查询'">
                  <el-descriptions title="用户信息">
                    <el-descriptions-item label="姓名">{{ item.content.name }}</el-descriptions-item>
                    <el-descriptions-item label="性别">{{ item.content.sex }}</el-descriptions-item>
                  </el-descriptions>
                  <el-descriptions >
                    <el-descriptions-item label="联系电话1">{{ item.content.phone }}</el-descriptions-item>
                    <el-descriptions-item label="联系电话2">{{ item.content.phoneTwo }}</el-descriptions-item>
                    <el-descriptions-item label="身份证号">{{ item.content.idCard }}</el-descriptions-item>
                    <el-descriptions-item label="其他联系人电话1">{{ item.content.phoneThree }}</el-descriptions-item>
                    <el-descriptions-item label="其他联系人电话2">{{ item.content.phoneFour }}</el-descriptions-item>
                    <el-descriptions-item label="出生日期">{{ item.content.birthday }}</el-descriptions-item>
                    <el-descriptions-item label="农历/公历">{{ item.content.birthdayType | birthdayTypeFilter }}</el-descriptions-item>
                    <el-descriptions-item label="年龄">{{ item.content.age }}</el-descriptions-item>
                    <el-descriptions-item label="来源">{{ sourceEnum.filter(tmpItem => tmpItem.id == item.content.source)[0].source }}</el-descriptions-item>
                    <el-descriptions-item label="介绍人" v-if="item.content.source == 1">{{ patientEnum.filter(tmpItem => tmpItem.id == item.content.introducer)[0].name }}</el-descriptions-item>
                    <el-descriptions-item label="介绍人" v-if="item.content.source == 2">{{ userEnum.filter(tmpItem => tmpItem.id == item.content.introducer)[0].name }}</el-descriptions-item>
                  </el-descriptions>
                  <el-form :model="item.content" label-width="120px" :rules="addPatientFormRules">
                    <el-row :gutter="10">
                      <!-- <el-col :span=8 >
                        <el-form-item label="编号">
                          <el-input v-model="addPatientForm.code" />
                        </el-form-item>
                      </el-col> -->
                      <el-col :span=8 >
                        <el-form-item label="姓名" prop="name">
                          <el-input v-model="item.content.name" :disabled="true" />
                        </el-form-item>
                      </el-col>
                      <el-col :span=6 >
                        <el-form-item label="性别" prop="sex">
                          <el-select v-model="item.content.sex" placeholder="请选择" :disabled="true" >
                            <el-option
                              v-for="item in sexEnum"
                              :key="item"
                              :label="item"
                              :value="item">
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="10">
                      <el-col :span=6 >
                        <el-form-item label="联系电话1" prop="phone" >
                          <el-input v-model="item.content.phone" @input="inputPhone" maxlength="11" :disabled="true" />
                        </el-form-item>
                      </el-col>
                      <el-col :span=6 >
                        <el-form-item label="联系电话2" >
                          <el-input v-model="item.content.phoneTwo" @input="inputPhone" maxlength="11" :disabled="true" />
                        </el-form-item>
                      </el-col>
                      <el-col :span=6 >
                        <el-form-item label="身份证号" prop="idCard">
                          <el-input style="width: 100%" v-model="item.content.idCard" @input="inputIdCard" maxlength="18" :disabled="true" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="10">
                      <el-col :span=6 >
                        <el-form-item label="其他联系人电话1" >
                          <el-input v-model="item.content.phoneThree" @input="inputPhone" maxlength="11" :disabled="true" />
                        </el-form-item>
                      </el-col>
                      <el-col :span=6 >
                        <el-form-item label="其他联系人电话2" >
                          <el-input v-model="item.content.phoneFour" @input="inputPhone" maxlength="11" :disabled="true" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="10">
                      <el-col :span=4 >
                        <el-form-item label="出生日期" prop="birthday">
                          <el-date-picker v-model="item.content.birthday" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" @change="changeBirthday" :disabled="true" ></el-date-picker>
                        </el-form-item>
                      </el-col>
                      <el-col :span=6 :offset=4>
                        <el-form-item label="农历/公历" prop="birthdayType">
                          <el-select v-model="item.content.birthdayType" placeholder="请选择" :disabled="true" >
                            <el-option
                              v-for="item in birthdayTypeEnum"
                              :key="item.id"
                              :label="item.name"
                              :value="item.id">
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span=6 >
                        <el-form-item label="年龄">
                          <el-input v-model="item.content.age" type="Number" min=0 :disabled="true" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="10">
                      <el-col :span=8 >
                        <el-form-item label="来源" prop="source">
                          <el-select v-model="item.content.source" placeholder="请选择" :disabled="true" >
                            <el-option
                              v-for="item in sourceEnum"
                              :key="item.id"
                              :label="item.source"
                              :value="item.id"
                              >
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span=8 >
                        <el-form-item label="介绍人" v-if="item.content.source == 1 || item.content.source == 2" >
                          <el-select v-if="item.content.source == 1" v-model="item.content.introducer" placeholder="请选择" :disabled="true">
                            <el-option
                              v-for="item in patientEnum"
                              :key="item.id"
                              :label="item.code + ' - ' +item.name"
                              :value="item.id">
                            </el-option>
                          </el-select>
                          <el-select v-else-if="item.content.source == 2" v-model="item.content.introducer" placeholder="请选择" :disabled="true">
                            <el-option
                              v-for="item in userEnum"
                              :key="item.id"
                              :label="item.jobNumber + ' - ' + item.name"
                              :value="item.id">
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <div style="width:100%;border: 2px solid #E4E7ED;padding: 10px;">
                      <div v-for="(address, index) in item.content.addressList" :key="index" >
                        <el-row :gutter="10" v-if="index != 0">
                          <el-col :span=6>
                            <el-form-item label="多址说明" prop="multiAddressDes">
                              <el-select v-model="address.multiAddressDes" placeholder="请选择" :disabled="true" >
                                <el-option
                                  v-for="item in multiAddressDesEnum"
                                  :key="item"
                                  :label="item"
                                  :value="item"
                                >
                                </el-option>
                              </el-select>
                            </el-form-item>
                          </el-col>
                          <el-col :span=6>
                            <el-form-item label="说明填写" v-if="address.isOtherAddress == 1" prop="multiAddressDesOther">
                              <el-input v-model="address.multiAddressDesOther" :disabled="true"/>
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row :gutter="10">
                          <el-col :span=8 >
                            <el-form-item label="省/市/区" prop="addressPre" >
                              <el-cascader
                                :disabled="true"
                                size="large"
                                :options="options"
                                v-model="address.addressPre"
                                :props="{ value: 'label', label: 'label'}"
                                >
                              </el-cascader>
                            </el-form-item>
                          </el-col>
                          <el-col :span=6>
                            <el-form-item label="小区" prop="addressMid">
                              <el-input v-model="address.addressMid" :disabled="true" ></el-input>
                            </el-form-item>
                          </el-col>
                          <el-col :span=10 >
                            <el-form-item label="详细地址" prop="addressInfo">
                              <el-input v-model="address.addressInfo" :disabled="true" ></el-input>
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row :gutter="10">
                          <el-col :span=8 >
                            <el-form-item label="距离" prop="retailStore">
                              <el-select v-model="address.retailStore" placeholder="门店请选择" :disabled="true" >
                                <el-option
                                  v-for="item in deptEnum"
                                  :key="item"
                                  :label="item"
                                  :value="item"
                                >
                                </el-option>
                              </el-select>
                            </el-form-item>
                          </el-col>
                          <el-col :span=8 >
                            <el-form-item label="公交站数" prop="distance">
                              <el-input v-model="address.distance" type="Number" min=0 :disabled="true" />
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-divider></el-divider>
                      </div>
                    </div>
                  </el-form>
                </div>

                <div v-if="item.content.patientTabsValue == '会员基础信息修改'">
                  <el-form ref="updatePatientForm" :model="item.content" label-width="120px" :rules="addPatientFormRules">
                    <el-row :gutter="10">
                      <!-- <el-col :span=8 >
                        <el-form-item label="编号">
                          <el-input v-model="item.content.code" />
                        </el-form-item>
                      </el-col> -->
                      <el-col :span=8 >
                        <el-form-item label="姓名" prop="name">
                          <el-input v-model="item.content.name" />
                        </el-form-item>
                      </el-col>
                      <el-col :span=6 >
                        <el-form-item label="性别" prop="sex">
                          <el-select v-model="item.content.sex" placeholder="请选择">
                            <el-option
                              v-for="item in sexEnum"
                              :key="item"
                              :label="item"
                              :value="item">
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="10">
                      <el-col :span=6 >
                        <el-form-item label="联系人电话1" prop="phone">
                          <el-input v-model="item.content.phone" @input="inputPhone" maxlength="11" />
                        </el-form-item>
                      </el-col>
                      <el-col :span=6 >
                        <el-form-item label="联系人电话2" >
                          <el-input v-model="item.content.phoneTwo" @input="inputPhone" maxlength="11" />
                        </el-form-item>
                      </el-col>
                      <el-col :span=6 >
                        <el-form-item label="身份证号" prop="idCard">
                          <el-input v-model="item.content.idCard" @input="inputIdCard" maxlength="18" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span=6 >
                        <el-form-item label="其他联系人电话1" >
                          <el-input v-model="item.content.phoneThree" @input="inputPhone" maxlength="11" />
                        </el-form-item>
                      </el-col>
                      <el-col :span=6 >
                        <el-form-item label="其他联系人电话2" >
                          <el-input v-model="item.content.phoneFour" @input="inputPhone" maxlength="11" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="10">
                      <el-col :span=6 >
                        <el-form-item label="出生日期" prop="birthday">
                          <el-date-picker v-model="item.content.birthday" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" @change="changeBirthday"></el-date-picker>
                        </el-form-item>
                      </el-col>
                      <el-col :span=6 :offset=2>
                        <el-form-item label="农历/公历" prop="birthdayType">
                          <el-select v-model="item.content.birthdayType" placeholder="请选择">
                            <el-option
                              v-for="item in birthdayTypeEnum"
                              :key="item.id"
                              :label="item.name"
                              :value="item.id">
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span=6 >
                        <el-form-item label="年龄">
                          <el-input v-model="item.content.age" type="Number" min=0 />
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="10">
                      <el-col :span=8 >
                        <el-form-item label="来源" prop="source">
                          <el-select v-model="item.content.source" placeholder="请选择">
                            <el-option
                              v-for="item in sourceEnum"
                              :key="item.id"
                              :label="item.source"
                              :value="item.id"
                              @click.native="changeSource(item.id, item.content)"
                              >
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span=8 >
                        <el-form-item label="介绍人" v-if="item.content.source == 1 || item.content.source == 2" >
                          <el-select v-if="item.content.source == 1" v-model="item.content.introducer" placeholder="请选择" :disabled="item.content.introducerDisable">
                            <el-option
                              v-for="item in patientEnum"
                              :key="item.id"
                              :label="item.code + ' - ' +item.name"
                              :value="item.id">
                            </el-option>
                          </el-select>
                          <el-select v-else-if="item.content.source == 2" v-model="item.content.introducer" placeholder="请选择" :disabled="item.content.introducerDisable">
                            <el-option
                              v-for="item in userEnum"
                              :key="item.id"
                              :label="item.jobNumber + ' - ' + item.name"
                              :value="item.id">
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <div style="width:100%;border: 2px solid #E4E7ED;padding: 10px;">
                      <div v-for="(address, index) in item.content.addressList" :key="index" >
                        <el-button type="danger" icon="el-icon-delete" circle @click="deleteAddress(address, item.content.addressList)"></el-button>
                        <el-row :gutter="10" v-if="index != 0">
                          <el-col :span=6>
                            <el-form-item label="多址说明" prop="multiAddressDes">
                              <el-select v-model="address.multiAddressDes" placeholder="请选择" >
                                <el-option
                                  v-for="item in multiAddressDesEnum"
                                  :key="item"
                                  :label="item"
                                  :value="item"
                                  @click.native="changeMultiAddressDes(item, address)"
                                >
                                </el-option>
                              </el-select>
                            </el-form-item>
                          </el-col>
                          <el-col :span=6>
                            <el-form-item label="说明填写" v-if="address.isOtherAddress == 1" prop="multiAddressDesOther">
                              <el-input v-model="address.multiAddressDesOther"/>
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row :gutter="10">
                          <el-col :span=8 >
                            <el-form-item label="省/市/区" prop="addressPre">
                              <el-cascader
                                size="large"
                                :options="options"
                                v-model="address.addressPre"
                                @change="handleChange"
                                :props="{ value: 'label', label: 'label'}"
                              >
                              </el-cascader>
                            </el-form-item>
                          </el-col>
                          <el-col :span=6>
                            <el-form-item label="小区" prop="addressMid">
                              <el-input v-model="address.addressMid"></el-input>
                            </el-form-item>
                          </el-col>
                          <el-col :span=10 >
                            <el-form-item label="详细地址" prop="addressInfo">
                              <el-input v-model="address.addressInfo"></el-input>
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row :gutter="10">
                          <el-col :span=6 >
                            <el-form-item label="距离" prop="retailStore">
                              <el-select v-model="address.retailStore" placeholder="门店请选择" >
                                <el-option
                                  v-for="item in deptEnum"
                                  :key="item"
                                  :label="item"
                                  :value="item"
                                >
                                </el-option>
                              </el-select>
                            </el-form-item>
                          </el-col>
                          <el-col :span=8 >
                            <el-form-item label="公交站数" prop="distance">
                              <el-input v-model="address.distance" type="Number" min=0 />
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-divider></el-divider>
                      </div>
                      <el-button type="primary" @click="updateFormAddAddress(item.content)">添加地址</el-button>
                    </div>
                    <el-button type="primary" @click="updateConfirm(item.content)">确 定</el-button>
                  </el-form>
                </div>

                <div v-if="item.content.patientTabsValue == '会员等级设置'">
                  会员等级设置内容
                </div>

                <div v-if="item.content.patientTabsValue == '会员就诊记录查询'">
                  会员就诊记录查询内容
                </div>

                </el-tab-pane>
              </el-tabs>

            </el-main>
            <el-aside width="220px">
              <el-menu
                @select="(key, keyPath) => handleSelect(key, keyPath, item.content)" 
                default-active="2"
                :default-openeds="defaultOpen"
                class="el-menu-vertical-demo"
                @open="handleOpen"
                @close="handleClose">
                <el-submenu index="1" >
                  <template slot="title">
                    <span style="font-weight: 600;font-size: 18px;">会员管理</span>
                  </template>
                    <el-menu-item index="会员基础信息查询" style="font-size: 14px">会员基础信息查询</el-menu-item>
                    <el-menu-item index="会员基础信息修改" style="font-size: 14px">会员基础信息修改</el-menu-item>
                    <el-menu-item index="会员等级设置" style="font-size: 14px">会员等级设置</el-menu-item>
                </el-submenu>
                <el-submenu index="2" >
                  <template slot="title">
                    <span style="font-weight: 600;font-size: 18px;">会员就诊记录查询</span>
                  </template>
                    <el-menu-item index="会员就诊记录查询" style="font-size: 14px">会员就诊记录查询</el-menu-item>
                </el-submenu>
              </el-menu>
            </el-aside>
          </el-container>
        </div>

      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>

import { getList, add, edit, del, getAllPatientList} from '@/api/patient'
import { regionData } from 'element-china-area-data'
import { getAllUserList} from '@/api/user'
import { getList as getSourceList} from '@/api/source'

export default {
  name: "Patient",
  filters: {
    birthdayTypeFilter(status) {
      const statusMap = ['', '阳', '阴']
      return statusMap[status]
    },
  },
  data() {
    const validateName = (rule, value, callback) => {
      if (!value) callback(new Error('请输入姓名')) 
      else callback()
    }
    const validatePhone = (rule, value, callback) => {
      if (!value) callback(new Error('请输入电话')) 
      else callback()
    }
    const validateIdCard = (rule, value, callback) => {
      if (!value) callback(new Error('请输入身份证号')) 
      else callback()
    }
    const validateSex = (rule, value, callback) => {
      if (!value) callback(new Error('请选择性别')) 
      else callback()
    }
    const validateBirthday = (rule, value, callback) => {
      if (!value) callback(new Error('请选择出生日期')) 
      else callback()
    }
    const validateBirthdayType = (rule, value, callback) => {
      if (!value) callback(new Error('请选择类型')) 
      else callback()
    }
    const validateSource = (rule, value, callback) => {
      if (!value) callback(new Error('请选择来源')) 
      else callback()
    }
    const validateAddressPre = (rule, value, callback) => {
      var flag = false
      for (const address of this.addPatientForm.addressList) {
        if(!address.addressPre || address.addressPre.length < 3) flag = true
      }
      if (flag) callback(new Error('地址不能为空')) 
      else callback()
    }
    const validateAddressMid = (rule, value, callback) => {
      var flag = false
      for (const address of this.addPatientForm.addressList) {
        if(!address.addressMid || address.addressMid==='') flag = true
      }
      if (flag) callback(new Error('小区不能为空')) 
      else callback()
    }
    const validateAddressInfo = (rule, value, callback) => {
      var flag = false
      for (const address of this.addPatientForm.addressList) {
        if(!address.addressInfo || address.addressInfo === '') flag = true
      }
      if (flag) callback(new Error('地址不能为空')) 
      else callback()
    }
    const validateMultiAddressDes = (rule, value, callback) => {
      var flag = false
      for (const address of this.addPatientForm.addressList) {
        if(!address.multiAddressDes) flag = true
      }
      if (flag) callback(new Error('多址选择不能为空')) 
      else callback()
    }
    const validateMultiAddressDesOther = (rule, value, callback) => {
      var flag = false
      for (const address of this.addPatientForm.addressList) {
        if(address.multiAddressDes == '其他' && (!address.multiAddressDesOther || address.multiAddressDesOther === '')) flag = true
      }
      if (flag) callback(new Error('其他原因不能为空')) 
      else callback()
    }
    const validateRetailStore = (rule, value, callback) => {
      var flag = false
      for (const address of this.addPatientForm.addressList) {
        if(!address.retailStore) flag = true
      }
      if (flag) callback(new Error('门店不能为空')) 
      else callback()
    }
    const validateDistance = (rule, value, callback) => {
      var flag = false
      for (const address of this.addPatientForm.addressList) {
        if(!address.distance && address.distance == '') flag = true
      }
      if (flag) callback(new Error('公交站数不能为空')) 
      else callback()
    }
    return {
      patientList: null,
      patientListLoading: true,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      curIndex: -1,
      infoVisible: false,
      addPatientformVisible: false,
      info: {},
      addPatientForm: {},
      query: {},
      dialogTitle: '添加来源',
      depts:[],
      addPatientFormRules: {
        name: [{ required: true, trigger: 'blur', validator: validateName }],
        phone: [{ required: true, trigger: 'blur', validator: validatePhone }],
        idCard: [{ required: true, trigger: 'blur', validator: validateIdCard }],
        sex: [{ required: true, trigger: 'blur', validator: validateSex }],
        birthday: [{ required: true, trigger: 'blur', validator: validateBirthday }],
        birthdayType: [{ required: true, trigger: 'blur', validator: validateBirthdayType }],
        source: [{ required: true, trigger: 'blur', validator: validateSource }],
        addressPre: [{ required: true, trigger: 'blur', validator: validateAddressPre }],
        addressMid: [{ required: true, trigger: 'blur', validator: validateAddressMid }],
        addressInfo: [{ required: true, trigger: 'blur', validator: validateAddressInfo }],
        multiAddressDes: [{ required: true, trigger: 'blur', validator: validateMultiAddressDes }],
        multiAddressDesOther: [{ required: true, trigger: 'blur', validator: validateMultiAddressDesOther }],
        retailStore: [{ required: true, trigger: 'blur', validator: validateRetailStore }],
        distance: [{ required: true, trigger: 'blur', validator: validateDistance }],
      },
      editableTabsValue: '1',
      editableTabs: [],
      patientTabsValue: '',
      patientTabs: [],
      sourceEnum: [],
      sexEnum: ["男", "女"],
      userEnum: [],
      patientEnum: [],
      options: regionData,
      birthdayTypeEnum:[{id: 1, name: '公历'}, {id: 2, name: '农历'}],
      multiAddressDesEnum: ["临时居住", "子女居所", "邮寄用地址", "其他"],
      deptEnum: ['劳动店', '永春店'],
      introducerDisable: true,
      defaultOpen: ['1', '2'],
      isWarnExistName: true,
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      getSourceList().then(sourceRes=>{
        this.sourceEnum = sourceRes.data
      })
      getAllPatientList().then(res=>{
        console.log("patient res:", res)
        this.patientEnum = res.data
      })
      getAllUserList().then(res=>{
        console.log("user res:", res)
        this.userEnum = res.data
      })
    },
    clickCurPage(val){
      this.currentPage = val
      this.fetchData()
    },
    getInfo(row) {
      this.info = row
      this.infoVisible = true
    },
    update(row) {
      this.reset()
      this.dialogTitle = '修改来源'
      this.form = JSON.parse(JSON.stringify(row))
      this.formVisible = true
    },
    
    cancel() {
      this.formVisible = false
    },
    reset(){
      this.form = {}
    },
    removeTab(targetName) {
      let tabs = this.editableTabs;
      let activeName = this.editableTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          console.log(tab.name)
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }
      
      this.editableTabsValue = activeName;
      this.editableTabs = tabs.filter(tab => tab.name !== targetName);
    },
    removePatientTab(targetName, patient) {
      let tabs = patient.patientTabs;
      let activeName = patient.patientTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }
      patient.patientTabsValue = activeName;
      patient.patientTabs = tabs.filter(tab => tab.name !== targetName);
    },
    queryPatient() {
      var list = this.editableTabs.filter(item => item.name == '1')
      if(list.length != 0) {
        this.editableTabsValue = '1'
        return
      }
      this.getPatientList({})
      this.editableTabs.push({
        title: '会员查询',
        name: '1',
        content: {},
      })
      this.editableTabsValue = '1'
    },
    addPatient() {
      var list = this.editableTabs.filter(item => item.name == '2')
      if(list.length != 0) {
        this.editableTabsValue = '2'
        return
      }
      this.$set(this.addPatientForm, 'addressList', [{}])
      this.editableTabs.push({
        title: '新增会员',
        name: '2',
        content: {},
      })
      this.editableTabsValue = '2'
    },
    search() {
      this.getPatientList({name: this.query.name})
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //  get patient list page function
    getPatientList(params) {
      this.patientListLoading = true
      params.currentPage = this.currentPage
      params.pageSize = this.pageSize 
      getList(params).then(res=>{
        this.patientList = res.data.records
        console.log(this.patientList)
        this.patientList.forEach(item=>{
          item.age = new Date().getFullYear() - item.birthday.substring(0,4)
          item.addressList.forEach(address=>{
            var addressPreArr = address.address.split('|||')
            address.addressPre = [addressPreArr[0], addressPreArr[1], addressPreArr[2]]
            this.$set(address, 'addressMid', addressPreArr[3])
            this.$set(address, 'addressInfo', addressPreArr[4])
          })
        })
        this.patientListLoading = false
      }).catch(err=>{
        console.log("err")
        console.log(err)
        this.patientListLoading = false
      })
      
    },
    //  add patient page function
    inputPhone() {
      var phone = this.addPatientForm.phone
      // this.addPatientForm.realPhone = JSON.parse(JSON.stringify(phone))
      // if(phone.length === 11) {
      //   this.addPatientForm.phone = phone.substring(0, 3) + '****' + phone.substring(7, 11)
      // }
    },
    inputIdCard() {
      var idCard = this.addPatientForm.idCard
      if(idCard.length === 18) {
        var ymd = idCard.substring(6, 14)
        this.$set(this.addPatientForm, 'birthday', ymd.substring(0,4) + '-' + ymd.substring(4,6) + '-' + ymd.substring(6,8))
        this.$set(this.addPatientForm, 'age', new Date().getFullYear() - ymd.substring(0,4))
      }
    },
    changeBirthday() {
      this.$set(this.addPatientForm, 'age', new Date().getFullYear() - this.addPatientForm.birthday.substring(0,4))
    },
    changeSource(sourceId, from) {
      this.$set(from, 'introducer', undefined)
      if(sourceId == 1 || sourceId == 2) {
        this.$set(from, 'introducerDisable', false)
      }else {
        this.$set(from, 'introducerDisable', true)
      }
    },
    handleChange (address) {
      console.log("address", address)
      this.$set(this.addPatientForm, 'addressPre', address)
    },
    addAddress() {
      this.addPatientForm.addressList.push({})
    },
    deleteAddress(address, list) {
      list.splice(list.indexOf(address), 1);
    },
    updateFormAddAddress(updateForm) {
      updateForm.addressList.push({})
    },
    changeMultiAddressDes(item, address) {
      if(item == '其他')  {
        this.$set(address, 'isOtherAddress', 1)
      } else {
        this.$set(address, 'isOtherAddress', 0)
      }
    },
    confirm() {
      this.$refs.addPatientForm[0].validate(valid => {
        if (valid) {
          console.log(this.addPatientForm)
          this.addPatientForm.addressList.forEach(address=>{
            address.type = 1
            address.address = address.addressPre[0] + '|||' + address.addressPre[1] + '|||' + address.addressPre[2] + '|||' + address.addressMid + '|||' + address.addressInfo
          })
          // 检查重复姓名
          getList({currentPage: 1, pageSize: 99999}).then(res=>{
            var allPatientList = res.data.records
            var existNamePatientList = allPatientList.filter(item=> item.name == this.addPatientForm.name)
            if(!existNamePatientList || existNamePatientList.length == 0) this.isWarnExistName = false
            if(this.isWarnExistName && existNamePatientList && existNamePatientList.length > 0) {
              this.isWarnExistName = false
              this.$confirm('已存在会员编号:'+ existNamePatientList[0].code + ' 姓名:' + existNamePatientList[0].name, '会员姓名重复！', {
                confirmButtonText: '继续提交',
                cancelButtonText: '返回修改',
                type: 'warning',
              }).then(() => {
                add(this.addPatientForm).then(res=>{
                  console.log(res)
                  this.$message({
                    message: '添加成功',
                    type: 'success'
                  })
                  this.addPatientForm = {}
                  this.removeTab("2")
                  this.editableTabsValue = "1"
                  this.getPatientList({})
                }).catch(err=>{
                  console.log(err)
                })
              }).catch(() => {
                this.addPatientForm.name = undefined
                this.$message({
                  type: 'info',
                  message: '请修改姓名'
                });          
              });;
              return
            }
            add(this.addPatientForm).then(res=>{
              console.log(res)
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              this.addPatientForm = {}
              this.removeTab("2")
              this.editableTabsValue = "1"
              this.getPatientList({})
            }).catch(err=>{
              console.log(err)
            })
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    updateConfirm(updateForm) {
      // this.$refs.updatePatientForm[0].validate(valid => {
      //   if (valid) {
          console.log(updateForm)
          updateForm.addressList.forEach(address=>{
            address.type = 1
            address.address = address.addressPre[0] + '|||' + address.addressPre[1] + '|||' + address.addressPre[2] + '|||' + address.addressMid + '|||' + address.addressInfo
          })
          edit(updateForm).then(res=>{
            console.log(res)
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            if(updateForm.phone && updateForm.phone.length == 11) updateForm.phone = updateForm.phone.substr(7)
            if(updateForm.phoneTwo && updateForm.phoneTwo.length == 11) updateForm.phoneTwo = updateForm.phoneTwo.substr(7)
            if(updateForm.phoneThree && updateForm.phoneThree.length == 11) updateForm.phoneThree = updateForm.phoneThree.substr(7)
            if(updateForm.phoneFour && updateForm.phoneFour.length == 11) updateForm.phoneFour = updateForm.phoneFour.substr(7)
            
            this.editableTabsValue = "1"
          }).catch(err=>{
            console.log(err)
          })
        // } else {
        //   console.log('error submit!!')
        //   return false
        // }
      // })
    },
    optionPatient(patient) {
      var list = this.editableTabs.filter(item => item.name == patient.code)
      if(list.length != 0) {
        this.editableTabsValue = patient.code
        return
      }
      this.$set(patient, 'patientTabsValue', '')
      this.$set(patient, 'patientTabs', [])
      patient.addressList = patient.addressList.filter(address => address.type == 1)
      this.editableTabs.push({
        title: patient.name,
        name: patient.code,
        content: patient
      })
      this.editableTabsValue = patient.code
    },

    /** patient detail page function */
    handleOpen(key, keyPath) {
      console.log(key, keyPath);
    },
    handleClose(key, keyPath) {
      console.log(key, keyPath);
    },
    handleSelect(key, keyPath, patient) {
      var list = patient.patientTabs.filter(item => item.name == key)
      if(list.length != 0) {
        patient.patientTabsValue = key
        return
      }

      patient.patientTabs.push({
        title: key,
        name: key,
        content: {}
      })
      patient.patientTabsValue = key
      console.log(patient.patientTabs)
      console.log(patient.patientTabsValue)
    }

  }
}
</script>


<style>
  .el-aside {
    width: 20%;
    text-align: center;
  }
  
  .el-main {
    width: 80%;
    text-align: left;
  }
  
  body > .el-container {
    margin-bottom: 40px;
  }
  .main-head-title {
    font-size: 14px;
  }
  
</style>